package bot.controller;

import bot.mapper.CptSendIdTableMapper;
import bot.pojo.CptSendIdTable;
import bot.pojo.CptSendIdTableExample;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.lang.reflect.Type;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/GPT")
public class ChatGPT {
    private CptSendIdTableExample cptSendIdTableExample = new CptSendIdTableExample();
    @Autowired
    private CptSendIdTableMapper cptSendIdTableMapper;
    static String defauleTyep = "";
    public static Map<String,String> map = new HashMap();
    //设置对话风格
    private long lastRunTime;
    @GetMapping("/sendGPT")
    public Object sendGPT(String content , @RequestParam("groupId") String gId ) {
        String status = accessAPI();
        if(status.equals("false")){
            return null;
        }
        sendData sendData = new sendData();
        //对话上下文id
        Options options = new Options();
        options.setModel(3);
        options.setUsingNetwork(false);
        //查询这个群是否有上下文id
        cptSendIdTableExample.clear();
        cptSendIdTableExample.createCriteria().andGIdEqualTo(gId);
        List<CptSendIdTable> cptSendIdTables = cptSendIdTableMapper.selectByExample(cptSendIdTableExample);
        if(cptSendIdTables.size() != 0){
            //sendData.setSystemMessage(cptSendIdTables.get(0).getSystemmessage());
            //options.setGroupId(Integer.valueOf(cptSendIdTables.get(0).getGroupId()));
            sendData.setAppId(cptSendIdTables.get(0).getAppid());
            options.setParentMessageId(cptSendIdTables.get(0).getSendId());
        }else{
            //没有就新增一条数据
            CptSendIdTable cptSendIdTable = new CptSendIdTable();
            cptSendIdTable.setgId(gId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm");
            cptSendIdTable.setCreateTime(simpleDateFormat.format(new Date()));
            cptSendIdTableMapper.insert(cptSendIdTable);
        }
        //拼接对话类型
        //content = defauleTyep + content;
        sendData.setOptions(options);
        sendData.setPrompt(content);
        String send = JSONObject.toJSONString(sendData);
        //新域名：https://vip-ai.slpan.cn/api/chat-process，旧https://vip.chat-gpt.bet/api/chat-process
        String s = HttpHelp.wlwHttpURLConnection("https://chat.julianwl.com/api/chatgpt/chat-process", send);
        if(s == null){
            returnData returnData = new returnData();
            returnData.setText("token可能过期，请及时更换");
            return returnData ;
        }
        //去掉最后一个逗号
        int index = s.lastIndexOf(",");
        s = s.substring(0,index);
        //json数组
        s = "["+ s +"]";
        //s = JSONObject.toJSONString(s);
        //把数据字符串转成对象
        JSONArray objects = JSONObject.parseArray(s);
        // 使用 Gson 将 JSONArray 转换成 List<returnData>
        Type listType = new TypeToken<ArrayList<returnData>>(){}.getType();
        ArrayList<returnData> users = new Gson().fromJson(objects.toString(), listType);
        int Lastsize = users.size();
        //记录每个群的bot对话上下文id
        cptSendIdTableExample.clear();
        cptSendIdTableExample.createCriteria().andGIdEqualTo(gId);
        List<CptSendIdTable> UpatacptSendIdTables = cptSendIdTableMapper.selectByExample(cptSendIdTableExample);
        UpatacptSendIdTables.get(0).setSendId(users.get(Lastsize - 1).getId());
        cptSendIdTableMapper.updateByPrimaryKey(UpatacptSendIdTables.get(0));
        //返回最后一条数据回去
        returnData returnData = users.get(Lastsize - 1);
        System.out.println(JSONObject.toJSONString(returnData));
        return JSONObject.toJSONString(returnData);
    }
    //清空对话id创建新会话
    @GetMapping("/delsend")
    public String delsend(String groupid){
        cptSendIdTableExample.clear();
        cptSendIdTableExample.createCriteria().andGIdEqualTo(groupid);
        List<CptSendIdTable> cptSendIdTables = cptSendIdTableMapper.selectByExample(cptSendIdTableExample);
        if(cptSendIdTables.size() > 0){
            cptSendIdTables.get(0).setSendId("");
            cptSendIdTableMapper.updateByPrimaryKey(cptSendIdTables.get(0));
            return "重置完成";
        }
        return "重置失败";
    }

    //展示当前对话风格
    @GetMapping("/getChatType")
    public String getChatType(){
        if(defauleTyep.equals("")){
            return "当前对话风格为default";
        }
        return "当前对话风格为"+defauleTyep;
    }
    //更新GPTToken
    @GetMapping("/tokenUpdata")
    public void tokenUpdata(String token){
       HttpHelp.GPTTOKEN ="Bearer"+ token;
        System.out.println("ok!");
    }
    //查看当前token值
    @GetMapping("/gettoken")
    public String gettoken(){
        System.out.println(HttpHelp.GPTTOKEN);
        return HttpHelp.GPTTOKEN;
    }
    static class returnData{
        private String role;
        private String id;
        private String text;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }
    class sendData{
        public Integer getAppId() {
            return appId;
        }

        public void setAppId(Integer appId) {
            this.appId = appId;
        }

        private Integer appId;
        private String prompt;

        private String systemMessage;
        private Options  options;

        public String getSystemMessage() {
            return systemMessage;
        }

        public void setSystemMessage(String systemMessage) {
            this.systemMessage = systemMessage;
        }

        public Options getOptions() {
            return options;
        }

        public void setOptions(Options options) {
            this.options = options;
        }

        public String getPrompt() {
            return prompt;
        }

        public void setPrompt(String prompt) {
            this.prompt = prompt;
        }
    }
    class Options{
        private Integer groupId;

        private Integer model;

        private Double temperature ;

        private Boolean usingNetwork;
        private String parentMessageId;

        public Integer getGroupId() {
            return groupId;
        }

        public void setGroupId(Integer groupId) {
            this.groupId = groupId;
        }

        public Integer getModel() {
            return model;
        }

        public void setModel(Integer model) {
            this.model = model;
        }

        public Double getTemperature() {
            return temperature;
        }

        public void setTemperature(Double temperature) {
            this.temperature = temperature;
        }

        public Boolean getUsingNetwork() {
            return usingNetwork;
        }

        public void setUsingNetwork(Boolean usingNetwork) {
            this.usingNetwork = usingNetwork;
        }

        public String getParentMessageId() {
            return parentMessageId;
        }

        public void setParentMessageId(String parentMessageId) {
            this.parentMessageId = parentMessageId;
        }
    }
    public String accessAPI(){
        long currentTime = System.currentTimeMillis();
        if(lastRunTime != 0){
            long timePassed = currentTime - lastRunTime;
            long time = timePassed/1000;
            //System.out.println("api调用过了 " + time + " 秒 ago.");
            //调用接口的间隔必须大于五秒钟
            if(time < 5){
                return "false";
            }
        }
        // 访问API，更新上次访问时间
        lastRunTime = currentTime;
        return "true";
    }
}
